const methodPermission = require('../config/permission')

function isAccessAllowed(user, setting) {
  const { role: userRole = [], permission: userPermission = [] } = user
  const { role: settingRole = [], permission: settingPermission = [] } = setting

  if (userRole.includes('admin')) {
    return
  }

  const hasRole =
    settingRole.length > 0 && settingRole.every((item) => !userRole.includes(item))
  const hasPermission =
    settingPermission.length > 0 &&
    settingPermission.every((item) => !userPermission.includes(item))

  // 有配置了role 或者 配置了permission
  if (hasRole || hasPermission) {
    return
  }

  throw {
    errCode: 403,
    errMsg: '无权限访问'
  }
}

module.exports = async function () {
  // 不在配置列表里面，不受权限控制
  const methodName = this.getMethodName()
  if (!(methodName in methodPermission)) {
    return
  }

  // 获取特定方法的权限
  const { role, permission } = methodPermission[methodName]

  // 没写role, 没写permission ,或者都是空列表，表示全部可以访问
  if (
    (!role && !permission) ||
    (role && role.length === 0 && permission && permission.length === 0)
  ) {
    return
  }

  return isAccessAllowed(this.authInfo, {
    role,
    permission
  })
}
